import * as config from './Config/Config';
const {
    target
} = config;
const Tool = {};
import {
    HttpService,
    Toast
} from './Http';

//线上线下切换
const online = true //线上
// const online = false //线下

//默认线上地址
export let goJxtUrl = 'http://sxt.17find.com'; //家校通跳转
export let AjaxUploadImgUrl = 'http://101.37.77.7/php/filedownload_image.php?FileId='; //PHP文件地址

if (!online) {
    // goJxtUrl = 'http://192.168.2.11:1780';
    goJxtUrl = 'http://192.168.2.31:1235';

    AjaxUploadImgUrl = 'http://192.168.2.11:1235/php/filedownload_image.php?FileId=';
}

/**
 * 发送ajax请求和服务器交互
 * @param {object} mySetting 配置ajax的配置
 */
Tool.ajax = function(mySetting) {

    var setting = {
        url: window.location.pathname, //默认ajax请求地址
        async: true, //true。默认设置下，所有请求均为异步请求。如果需要发送同步请求，请将此选项设置为 false
        type: 'GET', //请求的方式
        data: {}, //发给服务器的数据
        dataType: 'json',
        success: function(text) {}, //请求成功执行方法
        error: function() {} //请求失败执行方法
    };

    var aData = []; //存储数据
    var sData = ''; //拼接数据
    //属性覆盖
    for (var attr in mySetting) {
        setting[attr] = mySetting[attr];
    }
    for (var attr in setting.data) {
        aData.push(attr + '=' + filter(setting.data[attr]));
    }
    sData = aData.join('&');
    setting.type = setting.type.toUpperCase();

    var xhr = new XMLHttpRequest();
    try {
        if (setting.type == 'GET') { //get方式请求
            sData = setting.url + '?' + sData;
            xhr.open(setting.type, sData + '&' + new Date().getTime(), setting.async);
            xhr.send();
        } else { //post方式请求
            xhr.open(setting.type, setting.url, setting.async);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(sData);
        }
    } catch (e) {
        return httpEnd();
    }

    if (setting.async) {
        xhr.addEventListener('readystatechange', httpEnd, false);
    } else {
        httpEnd();
    }

    function httpEnd() {
        if (xhr.readyState == 4) {
            var head = xhr.getAllResponseHeaders();
            var response = xhr.responseText;
            //将服务器返回的数据，转换成json

            if (/application\/json/.test(head) || setting.dataType === 'json' && /^(\{|\[)([\s\S])*?(\]|\})$/.test(response)) {
                response = JSON.parse(response);
            }

            if (xhr.status == 200) {
                setting.success(response, setting, xhr);
            } else {
                setting.error(setting, xhr);
            }
        }
    }
    xhr.end = function() {
        xhr.removeEventListener('readystatechange', httpEnd, false);
    }

    function filter(str) { //特殊字符转义
        str += ''; //隐式转换
        str = str.replace(/%/g, '%25');
        str = str.replace(/\+/g, '%2B');
        str = str.replace(/ /g, '%20');
        str = str.replace(/\//g, '%2F');
        str = str.replace(/\?/g, '%3F');
        str = str.replace(/&/g, '%26');
        str = str.replace(/\=/g, '%3D');
        str = str.replace(/#/g, '%23');
        return str;
    }
    return xhr;
};
/**
 * 封装ajax post请求
 * @param {string} pathname 服务器请求地址
 * @param {object} data     发送给服务器的数据
 * @param {function} success  请求成功执行方法
 * @param {function} error    请求失败执行方法
 */
Tool.post = function(pathname, data, success, error) {
    var setting = {
        url: target + pathname, //默认ajax请求地址
        type: 'POST', //请求的方式
        data: data, //发给服务器的数据
        success: success || function() {}, //请求成功执行方法
        error: error || function() {} //请求失败执行方法
    };
    return Tool.ajax(setting);
};
/**
 * 封装ajax get请求
 * @param {string} pathname 服务器请求地址
 * @param {object} data     发送给服务器的数据
 * @param {function} success  请求成功执行方法
 * @param {function} error    请求失败执行方法
 */
Tool.get = function(pathname, data, success, error) {
    var setting = {
        url: target + pathname, //默认ajax请求地址
        type: 'GET', //请求的方式
        data: data, //发给服务器的数据
        success: success || function() {}, //请求成功执行方法
        error: error || function() {} //请求失败执行方法
    };
    return Tool.ajax(setting);
};

/**
 * 格式化时间
 *
 * @param {any} t
 * @returns
 */
Tool.formatDate = function(str) {
    var date = new Date(str);
    var time = new Date().getTime() - date.getTime(); //现在的时间-传入的时间 = 相差的时间（单位 = 毫秒）
    if (time < 0) {
        return '';
    } else if (time / 1000 < 60) {
        return '刚刚';
    } else if ((time / 60000) < 60) {
        return parseInt((time / 60000)) + '分钟前';
    } else if ((time / 3600000) < 24) {
        return parseInt(time / 3600000) + '小时前';
    } else if ((time / 86400000) < 31) {
        return parseInt(time / 86400000) + '天前';
    } else if ((time / 2592000000) < 12) {
        return parseInt(time / 2592000000) + '月前';
    } else {
        return parseInt(time / 31536000000) + '年前';
    }
}

/**
 * 本地数据存储或读取
 *
 * @param {any} key
 * @param {any} value
 * @returns
 */
Tool.localItem = function(key, value) {
    if (arguments.length == 1) {
        return localStorage.getItem(key);
    } else {
        return localStorage.setItem(key, value);
    }
}

/**
 * 删除本地数据
 *
 * @param {any} key
 * @returns
 */
Tool.removeLocalItem = function(key) {
    if (key) {
        return localStorage.removeItem(key);
    }
    return localStorage.removeItem();
}

Tool.assign = function(...args) {
    let from,
        target = args[0] || {},
        length = args.length;
    for (let i = 0; i < length; i++) {
        if ((from = args[i]) != null) {
            for (let key in from) {
                target[key] = from[key];
            }
        }
    }
    return target;
};


const goJxtFn = (url = `${goJxtUrl}/jiaxiaotong/#/index`, type, addUrl = '', sendData = {}) => {
    //type=1班主任，2老师，3家长
    localStorage.goback = 1;
    let phone = localStorage.userphone,
        goUrl = `${url}?wherefrom=weixin&babyid=${localStorage.babyid}&appToken=${localStorage.appToken}&orgname=${encodeURIComponent(localStorage.schoolName)}`;
    if (type == 3) {
        goUrl += addUrl;
        phone = localStorage.adminTelephone;
    }
    goUrl += '&phone=' + phone + '&appType=' + [2, 3, 1][type - 1] //type转换
    delete sessionStorage.mapinit

    location.href = encodeURI(goUrl);
}

import $ from 'jquery'
const loginJxt = (studentid, callback = () => {}) => {
    if (!studentid) {
        callback(false)
        return
    }
    let data = `method=ajaxJybJSON_999PassLogin&token=${localStorage.appToken}&passid=${localStorage.adminTelephone}&studentid=${studentid}&type=1`;
    if (localStorage.teacher == 1) { //教师登录
        if (sessionStorage.ticket) {
            callback(true)
            return
        }
        data = `method=ajaxJybJSON_999PassLogin&token=${localStorage.appToken}&passid=${localStorage.userphone}&type=${[2, 3, 1][studentid-1]}`;
    }
    $.ajax({
        url: goJxtUrl + '/jxt-commonbackground/ajaxLoginSystem.do?' + data,
        type: 'get',
        dataType: 'json',
        success: function(res) {
            if (res.code == 0) {
                sessionStorage.ticket = res.r.ticket;
                sessionStorage.newLoad = 1;
                localStorage.schoolName = res.r.detail.orgName;
                console.log(res)
                callback(true)
            } else {
                sessionStorage.newLoad = 0;
                delete sessionStorage.ticket;
                callback(false)
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            callback(false)
        }
    })
}
export const AjaxUploadImg = (file, callBack) => {
    let data = new FormData();
    data.append('Filedata', file, file.filename);
    $.ajax({
        url: 'http://101.37.77.7/php/fileuploadUUID.php?AppId=0&AppCode=0&UserName=public',
        type: 'POST',
        data: data,
        cache: false,
        //dataType:'jsonp',
        contentType: false, //不可缺
        processData: false, //不可缺
        success: function(res) {
            const status = res.split(':')[0],
                msg = res.split(':')[1];
            callBack({
                status,
                msg
            })
        }
    })
};
//URL获取关键字内容
export const urlKey = (keyName, newStr = location.href) => {
    if (newStr.indexOf('#') > -1)
        newStr = newStr.split('#')[0]
    var reg = new RegExp(keyName + '=([^&]*)(&|$)', 'i');
    var keyValue = reg.test(newStr) ?
        reg.exec(newStr)[1] :
        '';
    return keyValue.replace(/\s/ig, '');
};
//URL获取关键字内容
export const urlData = () => {
    // const hash = location.hash.slice(1)
    // if (urlKey('appToken', hash) == '')
    //     return
    // localStorage.appToken = urlKey('appToken', hash)
    // localStorage.userphone = urlKey('userphone', hash)
    // localStorage.babyid = urlKey('babyid', hash)
    // localStorage.schoolName = urlKey('orgname', hash)
};

/**
 * 判断是否为iphone4或iphone4s
 */
export const isIphone4 = () => {
    // 判断是否 iPhone 且 为phone4或iphone4s
    if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) && (window.screen.width == 320 && window.screen.height == 480)) {
        // 判断系统版本号是否在5~9间，ios10支持iphone5+
        return Boolean(navigator.userAgent.match(/OS [5-9]_\d[_\d]* like Mac OS X/i));
    } else {
        return false;
    }
};
/**
 * 图片加载失败时加载默认图片
 * @param e
 */
export const imgOnError = (defaultHeadImg, e) => {
    e.target.src = defaultHeadImg;
};
/**
 * 获取当前时间
 * @param format :yyyy-MM-dd HH:MM:SS yyyy-MM-dd MM-dd HH:MM:SS HH:MM MM:SS
 * @return newDate(yyyy-MM-dd HH:MM:SS)
 */
export const getNowFormatDate = (format = 'yyyy-MM-dd HH:MM:SS', time = new Date()) => {
    let date = new Date(time);
    let seperator1 = "-";
    let seperator2 = ":";
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    let getHours = date.getHours();
    let getMinutes = date.getMinutes();
    let getSeconds = date.getSeconds();

    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (getHours >= 0 && getHours <= 9) {
        getHours = "0" + getHours;
    }
    if (getMinutes >= 0 && getMinutes <= 9) {
        getMinutes = "0" + getMinutes;
    }
    if (getSeconds >= 0 && getSeconds <= 9) {
        getSeconds = "0" + getSeconds;
    }

    let currentdate = '';
    switch (format) {
        case 'MM-dd':
            currentdate = month + seperator1 + strDate;
            break;
        case 'yyyy-MM':
            currentdate = date.getFullYear() + seperator1 + month;
            break;
        case 'yyyy-MM-dd':
            currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
            break;
        case 'HH:MM':
            currentdate = getHours + seperator2 + getMinutes;
            break;
        case 'HH:MM:SS':
            currentdate = getHours + seperator2 + getMinutes + seperator2 + getSeconds;
            break;
        case 'MM:SS':
            currentdate = getMinutes + seperator2 + getSeconds;
            break;
        default:
            currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + getHours + seperator2 + getMinutes + seperator2 + getSeconds;
            break;
    }
    return currentdate;
};
/**
 * 根据日期字符串获取星期几
 * @param dateString 日期字符串（如：2016-12-29），为空时为用户电脑当前日期
 * @returns {String}
 */
export const getWeek = (dateString) => {
    var date;
    if (isNull(dateString)) {
        date = new Date();
    } else {
        var dateArray = dateString.split("-");
        date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
    }
    //var weeks = new Array("日", "一", "二", "三", "四", "五", "六");
    //return "星期" + weeks[date.getDay()];
    return "星期" + "日一二三四五六".charAt(date.getDay());
};
/**
 * 是否为Null
 * @param object
 * @returns {Boolean}
 */
export const isNull = (object) => {
    if (object == null || typeof object == "undefined") {
        return true;
    }
    return false;
};
/**
 * 获取一月多少天
 * @param date
 * @return {number}
 */
export const getCountDays = (date = getNowFormatDate()) => {
    var curDate = new Date(date);
    /* 获取当前月份 */
    var curMonth = curDate.getMonth();
    /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
    curDate.setMonth(curMonth + 1);
    curDate.setDate(0);
    /* 返回当月的天数 */
    return curDate.getDate();
};


//获取积分入口
export const integralSwitch = (data, callBack) => {
    HttpService.query({
        url: '/jf/entrance/getStatus',
        data,
        success: (res => {
            if (res.code == 10140)
                callBack(res.data.status, res)
        })
    });
}
export {
    Tool,
    config,
    goJxtFn,
    loginJxt
}
